package com.easy.dn.ui.main.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.easy.common.base.BaseActivity;
import com.easy.common.baserx.RxBus;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.dn.app.AppConstant;
import com.easy.dn.bean.JobAddressBean;
import com.easy.dn.bean.ListBean;
import com.easy.dn.ui.main.adapter.AddressTopSelectAdapter;
import com.easy.dn.ui.main.adapter.AddressTypeAdapter;
import com.easy.dn.ui.main.contract.AddressTypeContract;
import com.easy.dn.ui.main.model.AddressTypeModel;
import com.easy.dn.ui.main.presenter.AddressTypePresenter;
import com.easy.dn.utils.DnUtils;
import com.easy.dn.utils.SerializableMap;
import com.easy.dn.widget.ClearEditText;
import com.easy.dn.widget.WaveSideBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import dn.easy.com.easyto.R;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 *
 * 地点
 * @author DN
 * @data 2017/7/26
 */
public class AddressTypeActivity extends BaseActivity<AddressTypePresenter, AddressTypeModel> implements
        AddressTypeContract.View, AdapterView.OnItemClickListener
        , StickyListHeadersListView.OnHeaderClickListener
        , StickyListHeadersListView.OnStickyHeaderChangedListener
        , StickyListHeadersListView.OnStickyHeaderOffsetChangedListener, DnToolbar.OnRightTitleClickListener {

    @Bind(R.id.toolbar)
    DnToolbar mToolbar;
    @Bind(R.id.clearEditText)
    ClearEditText mClearEditText;
    @Bind(R.id.select_number)
    TextView mSelectNumber;
    @Bind(R.id.check_gone)
    CheckBox mCheckGone;
    @Bind(R.id.recy_top_select)
    RecyclerView mRecyTopSelect;
    @Bind(R.id.linear_viewOrGone)
    LinearLayout mLinearViewOrGone;
    @Bind(R.id.list)
    StickyListHeadersListView mListView;
    @Bind(R.id.side_bar)
    WaveSideBar mSideBar;
    private ListBean mListBean  = new ListBean();
    private List<JobAddressBean> mList = new ArrayList<>();
    private List<JobAddressBean> mAllList = new ArrayList<>();
    private AddressTypeAdapter mAddressTypeAdapter;
    private List<JobAddressBean> mSelectList = new ArrayList<>();
    private int mMaxNum = 5;
    private AddressTopSelectAdapter mTopSelectAdapter;
    private String mIsWhere;
    private SerializableMap mSerializableMap = new SerializableMap();
    private SerializableMap mSelectMap;

    @Override
    public int getLayoutId() {
        return R.layout.act_adress_type;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {

        initTitle();
        mToolbar.setMainTitle(R.string.search_place);
        mToolbar.setOnRightTitleClickListener(this);
        mToolbar.setMainTitleRightText(R.string.save);

        Bundle bundle = getIntent().getExtras();
        mIsWhere = bundle.getString(AppConstant.ADDRESSTYPE);
        mMaxNum = bundle.getInt("maxNum");
        mSelectMap = (SerializableMap) bundle.getSerializable("map");
        if (mSelectMap != null) {
            Map<String, List<JobAddressBean>> jobAddressMap = mSelectMap.getMap();
            mSelectList = jobAddressMap.get(mIsWhere);
        }
        mPresenter.getData(mSelectList);
        initTopSelectData();
//        mSideBar.setMaxOffset(100);
//        mSideBar.setLazyRespond(true);
        /**
         *  侧边快速索引 SideBar
         */
        mSideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {
                Log.d("WaveSideBar", index.toUpperCase() + "");
                // Do something here ....
                //side index更改list位置  mListView.setSelectionFromTop(i, 0);
                for (int i = 0; i < mList.size(); i++) {
                    if (index.equals(AppConstant.ADDRESSALL)) {
                        if (mList.get(i).getIsWhare().equals(AppConstant.CHINA)) {
                            mListView.setSelectionFromTop(i, 0);
                            return;
                        }
                    } else if (index.equals(AppConstant.ADDRESSHOT)) {
                        if (mList.get(i).getIsWhare().equals(AppConstant.CHINA)) {
                            mListView.setSelectionFromTop(i, 0);
                            return;
                        }
                    } else if (index.equals(AppConstant.ADDRESSOTHER)) {
                        if (mList.get(i).getIsWhare().equals(AppConstant.ADDRESSOTHER)) {
                            mListView.setSelectionFromTop(i, 0);
                            return;
                        }
                    } else {
//                        String name = mList.get(i).getSpelling().substring(0,1); i>5过滤掉热门 和中国
                        if (index.toUpperCase().equals(mList.get(i).getSpelling().substring(0, 1).toUpperCase()) && i > 5) {
                            mListView.setSelectionFromTop(i, 0);
                            return;
                        }
                    }
                }
            }
        });


        //过滤关键字 搜索功能
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                filterData(charSequence.toString());
            }


            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    /**
     * @param filterString 过滤文字
     */
    private void filterData(String filterString) {
         List<JobAddressBean> lsit = new ArrayList<>();
        if (filterString==null||"".equals(filterString)){
            mSideBar.setVisibility(View.VISIBLE);
//            mPresenter.getData(mSelectList);
////            List data = listBean.getData();
//            mList.clear();
//            mList = mListBean.getData();
            mAddressTypeAdapter.notifyData(mList);
        }else {
            List<JobAddressBean> filterList = new ArrayList<>();
            for (JobAddressBean jobAddressBean : mList){
                if (jobAddressBean.getName().toLowerCase().contains(filterString.toLowerCase())){
                    filterList.add(jobAddressBean);
                }
            }
            if (filterList.size()>0){
//                mList.clear();
//                mList = filterList;
                mSideBar.setVisibility(View.GONE);
                mAddressTypeAdapter.notifyData(filterList);
            }
        }
    }

    /**
     * 初始化top選中 數據相关
     */
    private void initTopSelectData() {
        mTopSelectAdapter = new AddressTopSelectAdapter(R.layout.item_top_select, mSelectList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyTopSelect.setLayoutManager(layoutManager);
        mRecyTopSelect.setAdapter(mTopSelectAdapter);
        mSelectNumber.setText(getResources().getString(R.string.selected_place) + mSelectList.size() + "/" + mMaxNum);
        mCheckGone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCheckGone.setText(getResources().getString(R.string.selected_close));
                    mLinearViewOrGone.setVisibility(View.VISIBLE);
                } else {
                    mCheckGone.setText(getResources().getString(R.string.selected_open));
                    mLinearViewOrGone.setVisibility(View.GONE);
                }
            }
        });

        /**
         *  顶部已选中数据 点击去除状态
         */
        mTopSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JobAddressBean jobAddressBean = mSelectList.get(position);
                jobAddressBean.setIsChecked(false);
                refreshSelectData(false, jobAddressBean.getName());
                mSelectList.remove(jobAddressBean);
                mAddressTypeAdapter.notifyDataSetChanged();
                mTopSelectAdapter.setNewData(mSelectList);
                mSelectNumber.setText(getResources().getString(R.string.selected_place) + mSelectList.size() + "/" + mMaxNum);
            }
        });

    }

    // 返回地址列表
    @Override
    public void returnAddressList(ListBean listBean) {
        mList = listBean.getData();
        mListBean.setData(mList);
//        mAddressTypeAdapter.notifyDataSetChanged();
        mAddressTypeAdapter = new AddressTypeAdapter(this, mList);
        mListView.setOnItemClickListener(this);
        mListView.setOnHeaderClickListener(this);
        mListView.setOnStickyHeaderChangedListener(this);
        mListView.setOnStickyHeaderOffsetChangedListener(this);
        mListView.setDrawingListUnderStickyHeader(false);
        mListView.setAreHeadersSticky(true);
        mListView.setAdapter(mAddressTypeAdapter);
    }

    @Override
    public void returnSelectProfessionList(ListBean listBean) {
        mAddressTypeAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.title_check);
//        JobAddressBean jobAddressBean = mList.get(i);
        JobAddressBean jobAddressBean = (JobAddressBean) adapterView.getItemAtPosition(i);
        if (checkBox.isChecked()) {
            jobAddressBean.setIsChecked(false);
            checkBox.setChecked(false);
            mSelectList.remove(removeData(jobAddressBean.getName()));
            refreshSelectData(false, jobAddressBean.getName());
        } else {
            //中国单选
            if (jobAddressBean.getSpelling().equals("zhongguo")) {
                for (JobAddressBean bean : mList) {
                    bean.setIsChecked(false);
                    mSelectList.clear();
                }
                jobAddressBean.setIsChecked(true);
                checkBox.setChecked(true);
                refreshSelectData(true, jobAddressBean.getName());
                mSelectList.add(jobAddressBean);
            } else {
                if (mSelectList.size() < mMaxNum) {
                    for (JobAddressBean bean : mList) {
                        if (bean.getSpelling().equals("zhongguo")) {
                            bean.setIsChecked(false);
                            mSelectList.remove(bean);
                        }
                    }
                    jobAddressBean.setIsChecked(true);
                    checkBox.setChecked(true);
                    mSelectList.add(jobAddressBean);
                    refreshSelectData(true, jobAddressBean.getName());
                } else {
                    DnUtils.showToast(mClearEditText, this.getResources().getString(R.string.noChoose));
                }
            }
            mAddressTypeAdapter.notifyDataSetChanged();
        }

        notifyTopSelectList();
    }

    /**
     * 更新顶部选中数据
     */
    private void notifyTopSelectList() {
        mSelectNumber.setText(getResources().getString(R.string.selected_place) + mSelectList.size() + "/" + mMaxNum);
        mTopSelectAdapter.setNewData(mSelectList);
    }

    /**
     * 热门城市里面 北京上海 下面地点里面也包括 也需要改变他的状态
     *
     * @param isChecked         选中 or 取消
     * @param selectAddressName 选择的地点
     */
    private void refreshSelectData(Boolean isChecked, String selectAddressName) {
        for (JobAddressBean bean : mList) {
            if (bean.getName().equals(selectAddressName)) {
                bean.setIsChecked(isChecked);
            }
        }
    }


    /**
     * 根据名字删除
     *
     * @return 选中数据
     */
    private JobAddressBean removeData(String selectName) {
        for (JobAddressBean jobAddressBean : mSelectList) {
            if (jobAddressBean.getName().equals(selectName)) {
                return jobAddressBean;
            }
        }
        return null;
    }

    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId, boolean currentlySticky) {

    }

    @Override
    public void onStickyHeaderChanged(StickyListHeadersListView l, View header, int itemPosition, long headerId) {

    }

    @Override
    public void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset) {

    }

    @Override
    public void showLoading(String title) {
    }

    @Override
    public void stopLoading() {
    }

    @Override
    public void showErrorTip(String msg) {
        DnUtils.showToast(mClearEditText, msg);
    }

    @Override
    public void onRightClick(View view) {
        Map<String, List<JobAddressBean>> mselectMap = new HashMap<>();
        mselectMap.put(mIsWhere, mSelectList);
        mSerializableMap.setMap(mselectMap);
        RxBus.getInstance().post(mIsWhere, mSerializableMap);
        finish();
    }
    /**
     *  总结： 发现mvp使用才算是有点入门 并没有理解其中解耦的思想
     */
}
